package com.zf.zfed.audit.ui

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.zf.zfed.audit.R

/**
 * 条纹背景的LinearLayout
 * 为子视图提供交替的背景色
 */
class StripedLinearLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    override fun onViewAdded(child: View?) {
        super.onViewAdded(child)
        updateChildBackgrounds()
    }

    override fun onViewRemoved(child: View?) {
        super.onViewRemoved(child)
        updateChildBackgrounds()
    }

    private fun updateChildBackgrounds() {
        for (i in 0 until childCount) {
            val child = getChildAt(i)
            val backgroundColor = if (i % 2 == 0) {
                ContextCompat.getColor(context, R.color.background_set_item_light)
            } else {
                ContextCompat.getColor(context, R.color.background_set_item_dark)
            }
            child.setBackgroundColor(backgroundColor)
        }
    }
}
